package com.pap.rabbitmq.trans.config;

import com.pap.rabbitmq.trans.listener.TransDeadLetterMessageListener;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 绑定事务操作的死信队列
 *
 * @Auther: alexgaoyh
 * @Date: 2018/12/3 15:59
 * @Description:
 */
@Configuration
public class TransDeadQueueConfig {

    /**
     * 死信队列配置 交换机
     */
    private static final String TRANS_DLX_EXCHANGE = "TRANS_DLX_EXCHANGE";

    /**
     * 死信队列配置 队列
     */
    private static final String TRANS_DLX_QUEUE = "TRANS_DLX_QUEUE";

    /**
     * 死信队列配置 私信路由KEY
     */
    private static final String TRANS_DLX_ROUTING_KEY = "TRANS_DLX_ROUTING_KEY";


    //========================== 声明交换机 ==========================

    /**
     * 死信交换机
     */
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(TRANS_DLX_EXCHANGE);
    }


    //========================== 声明队列 ===========================

    /**
     * 死信队列
     */
    @Bean
    public Queue dlxQueue() {
        return new Queue(TRANS_DLX_QUEUE, true, false, false);
    }

    /**
     * 通过死信路由key绑定死信交换机和死信队列
     */
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange())
                .with(TRANS_DLX_ROUTING_KEY);
    }

    /**
     * 死信队列的监听
     *
     * @param connectionFactory              RabbitMQ连接工厂
     * @param transDeadLetterMessageListener 死信队列监听
     * @return 监听容器对象
     */
    @Bean
    public SimpleMessageListenerContainer deadLetterListenerContainer(ConnectionFactory connectionFactory,
                                                                      TransDeadLetterMessageListener transDeadLetterMessageListener) {

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(dlxQueue());
        container.setExposeListenerChannel(true);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener(transDeadLetterMessageListener);
        /** 设置消费者能处理消息的最大个数 */
        container.setPrefetchCount(100);
        return container;
    }
}
